package cn.leedsoft.luma.test.dynamic_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by Administrator on 2017/5/25.
 */
public class MyInvocationHandler implements InvocationHandler{
    private Object target;
    public MyInvocationHandler(Object target){
        this.target = target;//通过构造方法注入被代理对象target
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
        System.out.println("do something before");
        Object ret = method.invoke(target, objects);
        System.out.println("do something after");

        return ret;
    }

    public static Object getProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),//通过被代理对象，获得proxy instance
                obj.getClass().getInterfaces(), new MyInvocationHandler(obj));
    }
}
